package it.learn.kafka.infra.producer.interceptor;

import it.learn.kafka.infra.common.SomeBean;
import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Map;

public class MyProducerInterceptor implements ProducerInterceptor<String, String> {

    private SomeBean bean;

    @Override
    public void configure(Map<String, ?> configs) {
        this.bean = (SomeBean) configs.get("some.bean");
    }

    // 1、在消息被发送到Kafka集群之前调用
    // 2、返回值应是经过处理后的ProducerRecord对象，如果返回null，则该消息将不会被发送
    @Override
    public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) {
        this.bean.someMethod("producer interceptor");
        return record;
    }

    // 1、在消息成功发送并收到确认（ACK）或发送失败时调用
    // 2、此方法的执行是在Kafka生产者I/O线程上，因此应尽量避免在此方法中执行耗时操作
    @Override
    public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
    }

    @Override
    public void close() {
    }

}